#include "vim.h"
#include "misc2.h"
#include <stdlib.h>
#include <string.h>

static const char *crypt_magic[] = {"VimCrypt~01!", "VimCrypt~02!"};
//static const char crypt_magic_head[] = "VimCrypt~";
# define CRYPT_MAGIC_LEN	12		/* must be multiple of 4! */
//static int crypt_salt_len[1] = {0, 8};
//static int crypt_seed_len[2] = {0, 8};
#define CRYPT_SALT_LEN_MAX 8
#define CRYPT_SEED_LEN_MAX 8

void crypt_push_state();
void crypt_init_keys(char_u *key);

char_u* check_for_cryptkey(char_u *cryptkey, char_u *ptr, long *sizep, off_t *filesizep)
{
    if (cryptkey != NULL) {
        
        crypt_push_state();
        crypt_init_keys(cryptkey);
        
        *filesizep += CRYPT_MAGIC_LEN;
        *sizep -= CRYPT_MAGIC_LEN;
        memmove(ptr, ptr + CRYPT_MAGIC_LEN,
                    (unsigned long)*sizep);
    }
    
    return cryptkey;
}

void prepare_crypt_write(char_u *key)
{
    crypt_push_state(); 
    crypt_init_keys(key);
}

char *read_crypt_file(const char *filename, const char *key)
{
    FILE *fp = fopen(filename, "rb");
    fseek(fp, 0, SEEK_END);
    long len = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    
    char *str = malloc(len);
    fread(str, 1, len, fp);
    fclose(fp);
     
    off_t filesize = 0;
    printf("ReadCrypt: %s\n", str);
    
    check_for_cryptkey((char_u*)key, (char_u*)str, &len, &filesize);
    crypt_decode((char_u*)str, len);
    str[len] = '\0';
    
    crypt_pop_state();
    
    return str;
}

void write_crypt_file(const char *filename, const char *str, const char *key)
{
    prepare_crypt_write((char_u*)key);
    
    size_t len = strlen((const char*)str);
    char_u *dst = malloc(len+1);
    
    crypt_encode((char_u*)str, len, dst);
    
    FILE *file = fopen(filename, "wb");
    fwrite(crypt_magic[0], 1, 12, file);
    fwrite(dst, 1, len, file);
    fclose(file);
    
    free(dst);
    crypt_pop_state();
}
